package com.freshfresh.upload;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;

import com.hangyjx.util.AndroidUtil;
import com.hangyjx.util.DialogUtil;

public class FileUploadTask extends AsyncTask<String, Integer, String> {
	private Context context;
	private ProgressDialog pro;
	private Handler handler;

	protected void onPreExecute() {
		super.onPreExecute();
		
		pro = new ProgressDialog(context);
		pro.setMax(100);
		pro.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pro.setProgress(0);
		pro.setTitle("上传进度");
		pro.setCancelable(false);
		pro.show();

	}
	
	protected String doInBackground(String... arg0) {
		String urlStr = arg0[0];
		String filePath = arg0[1];
		String message = arg0[2];
		
		String upret = "fail";
		try{
			String end = "\r\n";
			String twoHyphens = "--";
			String boundary = "*****";
			URL url = new URL(urlStr);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setConnectTimeout(Constants.TIME_OUT);
			con.setReadTimeout(Constants.TIME_OUT);
			/* 允许Input、Output，不使用Cache */
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* 设置传送的method=POST */
			con.setRequestMethod("POST");
			/* setRequestProperty */
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			/* 设置DataOutputStream */
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; "
					+ "name=\"fileInfo\";filename=\"file.zip\""
					+ end);
			ds.writeBytes("Content-Type: application/x-zip-compressed"+ end);
			ds.writeBytes(end);
			/* 取得文件的FileInputStream */
			FileInputStream fStream = new FileInputStream(filePath);
			//得到文件的大小
			long total = fStream.available();
			/* 设置每次写入10240bytes */
			int bufferSize = 1024 * 10;
			byte[] buffer = new byte[bufferSize];
			int count = 0;
			int length = 0;
			/* 从文件读取数据至缓冲区 */
			while ((count = fStream.read(buffer)) != -1) {
				length += count;
				publishProgress((int) ((length / (float) total) * 100));
				/* 将资料写入DataOutputStream中 */
				ds.write(buffer, 0, count);
				 //为了演示进度,休眠500毫秒
				 Thread.sleep(50);
			}
			ds.writeBytes(end);
			/* close streams */
			fStream.close();
			
			if(message != null && !"".equals(message)){
				ds.writeBytes(twoHyphens + boundary + end);
				ds.writeBytes("Content-Disposition: form-data; "
						+ "name=\"info\""
						+ end);
				ds.writeBytes(end);
				ds.write(message.getBytes());
				ds.writeBytes(end);
			}
			
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
			
			ds.flush();
			/* 取得Response内容 */
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			upret = b.toString();
			//关闭流
			ds.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		return upret;
	}
	
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		//加载进度
		pro.setProgress(values[0]);
	}
	
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		if(pro != null && pro.isShowing()){
			pro.dismiss();
		}
		if(result.equals("success")){
			AndroidUtil.handlerto(handler, Constants.UPLOAD_SUCCESS);
		}else{
			DialogUtil.promptDialog(context, "连接中断，请重试！");
		}
	}

	public FileUploadTask(Context context, Handler handler) {
		super();
		this.context = context;
		this.handler = handler;
	}
}

